package com.cuijian.demo.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserService {

    // 模拟数据存储（实际项目中应使用数据库）
    private Map<Long, Map<String, Object>> userMap = new HashMap<>();
    private long idCounter = 1;

    public UserService() {
        // 初始化一些测试数据
        createUser("张三", "zhangsan@example.com");
        createUser("李四", "lisi@example.com");
    }

    public Object getUserList(int page, int size) {
        List<Map<String, Object>> users = new ArrayList<>(userMap.values());

        // 简单的分页逻辑
        int fromIndex = (page - 1) * size;
        if (fromIndex >= users.size()) {
            return new ArrayList<>();
        }

        int toIndex = Math.min(fromIndex + size, users.size());
        List<Map<String, Object>> pageData = users.subList(fromIndex, toIndex);

        Map<String, Object> result = new HashMap<>();
        result.put("list", pageData);
        result.put("total", users.size());
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", (int) Math.ceil((double) users.size() / size));

        return result;
    }

    public Object getUserById(Long id) {
        return userMap.get(id);
    }

    public boolean createUser(String name, String email) {
        try {
            Map<String, Object> user = new HashMap<>();
            user.put("id", idCounter);
            user.put("name", name);
            user.put("email", email);
            user.put("createTime", System.currentTimeMillis());

            userMap.put(idCounter, user);
            idCounter++;
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean updateUser(Long id, String name, String email) {
        Map<String, Object> user = userMap.get(id);
        if (user == null) {
            return false;
        }

        if (name != null) {
            user.put("name", name);
        }
        if (email != null) {
            user.put("email", email);
        }
        user.put("updateTime", System.currentTimeMillis());

        return true;
    }

    public boolean deleteUser(Long id) {
        return userMap.remove(id) != null;
    }
}